<template>
  <div class="app-container">
    <Find :OriginalFilter="{ static: true }" :formList="formList" @findClicked="findClicked" />
    <Find :searchImg="false" :OriginalFilter="{ static: true }" :formList="formList2" @findClicked="findClicked2" />
    <div class="flex mt10" style="width: 100%; background-color: white">
      <el-card shadow="never" :body-style="{ padding: '5px 10px 5px' }">
        <h1 class="f16">指令资料</h1>
        <Table
          @selectList="selectTableList"
          :summaryData="summaryData"
          summary
          :tableHeader="tableHeader"
          :tableData="tableData"
          selection
          class="mt10"
          :isLoading="isLoading"
          @currentRow="currentRow"
        />
        <PageModule :PageData="{ total, buttonS: true }" @pageSizeChange="handleSizeChange" @pageChange="handleCurrentChange" />
      </el-card>
      <el-card shadow="never" :body-style="{ padding: '5px 10px 5px' }">
        <div class="flex">
          <h1 class="f16 mr10">预算单价明细</h1>
          <JDialog
            v-if="!isCfmFlag"
            :tableHeader="JDialogHeader"
            :width="40"
            @removeOne="removeOne"
            :currentTableRow="currentTableRow2"
            @confirm="confirm"
            :unEdit="false"
          />
        </div>
        <Table @currentRow="currentRow2" :tableHeader="tableHeader2" :tableData="tableData2" selection class="mt10" :isLoading="isLoading2" />
      </el-card>
    </div>
  </div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import { selectList } from '@/plugins/mixin'
import { formateData } from '@/plugins/mixinJ'
import SynchronizationLoginWork from '@/utils/SynchronizationLoginWork'
import fileRequest from '@/utils/fileRequest'
import JMessage from '@/utils/JMessage'
export default defineComponent({
  name: 'ExternalUnitPriceInput'
})
</script>
<script lang="ts" setup>
import { i18n, Jzhcn } from '@/i18n'
import { ref } from 'vue'
import Api from '@/api/GeneralManager/Factory/ExternalUnitPrice'
import { ElMessage } from 'element-plus'
import Synchronization from '@/utils/Synchronization'
import { debounce } from 'lodash'
import { onMounted, watch } from 'vue'
const isCfmFlag = ref(false)
const formList = ref([
  {
    type: 'input',
    inputPlaceholder: '请输入指令',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入型体',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入客户',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'date',
    dateLabel: '下单日期',
    dateValue: ''
  },
  {
    type: 'date',
    dateLabel: '指令交期',
    dateValue: ''
  },
  {
    type: 'button',
    checkboxLabel: '置空',
    bgColor: '#1890FF'
  }
])
const formList2 = ref([
  {
    type: 'button',
    checkboxLabel: '导出预算明细'
  },
  {
    type: 'input',
    inputPlaceholder: '请输入外接单价',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'button',
    checkboxLabel: '插入外接单价'
  }
  // {
  //   type: 'input',
  //   inputPlaceholder: '请输入源指令',
  //   inputValue: '',
  //   inputLabel: '',
  // }, {
  //   type: 'button',
  //   checkboxLabel: '复制到勾选指令'
  // },
])
const tableHeader = ref([
  {
    label: '客户',
    prop: 'customer'
  },
  {
    width: '120',
    cfmFlag: '#00ff00',
    label: '指令',
    prop: 'lotNo'
  },
  {
    width: '120',
    label: '型体',
    prop: 'style'
  },
  {
    label: '颜色',
    prop: 'styleColor'
  },
  {
    label: '订单数',
    prop: 'orderQty'
  },
  {
    label: '下单日期',
    prop: 'customOrderDate'
  },
  {
    label: '交期',
    prop: 'deliveryDate',
    sortable: true
  },
  {
    width: '100',
    label: '制程',
    prop: 'process'
  },
  {
    label: '仲裁',
    prop: 'cutPrice'
  },
  {
    label: '手工',
    prop: 'craftPrice'
  },
  {
    label: '针车',
    prop: 'stitchPrice'
  },
  {
    label: '本厂单价',
    prop: 'costPrice'
  },
  {
    label: '外接单价',
    prop: 'outPrice'
  }
])
// 表一模块
// 表一按钮
const findClicked = async (content: string) => {
  if (content === '置空') {
    formList.value.forEach((item: any) => {
      item.inputValue = ''
      item.selectValue = ''
      item.dateValue = ''
    })
  }
}
const findClicked2 = async (content: string) => {
  if (content === '插入外接单价') {
    const res = (await SynchronizationLoginWork.put('/pcFactorWork/InsertExternalInitPrice', {
      lotNo: currentTableRow.value.lotNo,
      price: formList2.value[1].inputValue
    })) as any
    if (res.code === 200) {
      JMessage.success('插入成功')
      formList.value[7].inputValue = ''
    } else {
      JMessage.error(res.message)
    }
  }
  if (content === '导出预算明细') {
    const res = (await fileRequest.post(`/pcFactorWork/listPcDhPriceExcel?lotNo=${currentTableRow.value.lotNo}`)) as any
    const link = document.createElement('a') // 利用a标签自定义下载文件名
    let blob = new Blob([res.data]) // 创建Blob对象，设置文件类型
    link.style.display = 'none'
    //设置连接
    link.href = window.URL.createObjectURL(blob)
    link.download = decodeURIComponent(`${res.headers['content-disposition'].split("utf-8''")[1]}`) //自定义文件名字
    document.body.appendChild(link)
    //模拟点击事件
    link.click()
    document.body.removeChild(link)
  }
  if (content === '复制到勾选指令') {
  }
}
const tableData = ref([])
const imgList = ref([])
const isLoading = ref(true)
// 总计
// 总计
interface summaryDataType {
  index: number
  num: number | undefined
}
const summaryData = ref<summaryDataType[]>([
  {
    index: 5,
    num: 0
  },
  {
    index: 12,
    num: 0
  },
  {
    index: 13,
    num: 0
  }
])
// 分页器
const currentPage = ref(1)
const pageSize = ref(40)
const total = ref(0)
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getTableList()
}
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getTableList()
}
// 获取表数据
const getTableList = debounce(async () => {
  isLoading.value = true
  let tableDataList = await Synchronization.put<any, any>('/pcFactorWork/listDhHead', {
    brand: '',
    deliveryEndTime: formList.value.find(
      (item: any) => item.dateLabel && Jzhcn.Find[item.dateLabel.split('.')[1] as keyof typeof Jzhcn.Find] === '指令交期'
    )?.dateValue?.[1],
    deliveryStartTime: formList.value.find(
      (item: any) => item.dateLabel && Jzhcn.Find[item.dateLabel.split('.')[1] as keyof typeof Jzhcn.Find] === '指令交期'
    )?.dateValue?.[0],
    lotNo: formList.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '请输入指令'
    )?.inputValue,
    orderEndTime: formList.value.find(
      (item: any) => item.dateLabel && Jzhcn.Find[item.dateLabel.split('.')[1] as keyof typeof Jzhcn.Find] === '下单日期'
    )?.dateValue?.[1],
    orderStartTime: formList.value.find(
      (item: any) => item.dateLabel && Jzhcn.Find[item.dateLabel.split('.')[1] as keyof typeof Jzhcn.Find] === '下单日期'
    )?.dateValue?.[0],
    style: formList.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '请输入型体'
    )?.inputValue,
    pageNum: currentPage.value,
    pageSize: pageSize.value
  })
  imgList.value = tableDataList.dtos.map((item: any) => {
    return item.photoPath
  })
  tableData.value = tableDataList.dtos
  total.value = tableDataList.total
  currentRow()
  summaryData.value[0].num = tableDataList.orderQtySum
  summaryData.value[1].num = tableDataList.costPriceSum
  summaryData.value[2].num = tableDataList.outPriceSum
  isLoading.value = false
}, 500)
const getSelectList = async () => {
  await selectList(formList, Api.getSelectList)
}
onMounted(() => {
  getTableList()
  getSelectList()
})
watch(
  () =>
    formList.value.map((item: any) => {
      item.selectValue, item.inputValue, item.dateValue, item.checked
    }),
  () => {
    getTableList()
  }
)
// 点击表给另一张表传数据
const currentTableRow = ref({}) as any
const currentRow = async (row: any = tableData.value[0] ? tableData.value[0] : {}) => {
  if (row.cfmFlag === 'Y') isCfmFlag.value = true
  else isCfmFlag.value = false
  currentTableRow.value = row
  getTableList2()
  console.log(isCfmFlag.value)
}
const selectedLists = ref([])
const selectTableList = (selectedList: any) => {
  selectedLists.value = selectedList
}

// 表二模块
const tableData2 = ref([]) as any
const isLoading2 = ref(true)
const tableHeader2 = ref([
  {
    label: '预算项目',
    prop: 'process'
  },
  {
    label: '单价',
    prop: 'price'
  },
  {
    label: '备注',
    prop: 'remark'
  },
  {
    label: '建档日期',
    prop: 'slipDate',
    change: true
  },
  {
    label: '操作员',
    prop: 'sysUser',
    change: true
  }
])
const getTableList2 = async () => {
  isLoading2.value = true
  try {
    let data = await Api.getTableList2(currentTableRow.value.lotNo)
    tableData2.value = data.dtos
    currentRow2()
  } catch (error) {
    console.log(error)
  }
  isLoading2.value = false
}
const currentTableRow2 = ref({}) as any
const currentRow2 = async (row: any = tableData2.value[0]) => {
  currentTableRow2.value = row
}
// Dialog确认添加/修改按钮
const JDialogHeader = ref([
  {
    label: '预算项目',
    prop: 'process'
  },
  {
    label: '单价',
    prop: 'price'
  },
  {
    label: '备注',
    prop: 'remark'
  }
])
const confirm = async (obj: any, dialogVisible: any, title: any) => {
  // 打印出obj的值
  const tempList = formateData([obj]) as any
  const { style, color } = currentTableRow.value
  // 向服务器发送请求，更新外派单信息
  if (title === '添加') {
    const res = (await SynchronizationLoginWork.post(`/pcFactorWork/AddBudgetItem`, {
      lotNo: currentTableRow.value.lotNo,
      ...tempList[0]
    })) as any
    // 判断请求是否成功
    if (res.code === 200) {
      JMessage.success(res.message)
    } else {
      JMessage.error(res.message)
    }
  } else if (title === '修改') {
    const res = (await SynchronizationLoginWork.put(`/pcFactorWork/ModifyBudgetItems`, {
      lotNo: currentTableRow.value.lotNo,
      ...tempList[0]
    })) as any
    // 判断请求是否成功
    if (res.code === 200) {
      JMessage.success(res.message)
    } else {
      JMessage.error(res.message)
    }
  }
  // 关闭弹出框
  dialogVisible.value = false
  // 重新获取表格数据
  getTableList2()
}
// 删除
const removeOne = async () => {
  const { style, color } = currentTableRow.value
  // 向服务器发送请求，更新外派单信息
  const res = (await SynchronizationLoginWork.put(`/pcFactorWork/DeleteBudgetItems`, currentTableRow2.value)) as any
  // 判断请求是否成功
  if (res.code === 200) {
    JMessage.success(res.message)
  } else {
    JMessage.error(res.message)
  }
  // 重新获取表格数据
  getTableList2()
}
</script>

<style lang="less" scoped>
table {
  table-layout: auto !important;
}

:deep(.el-table__header) {
  width: 100% !important;
}

:deep(.el-table__body) {
  width: 100% !important;
}

:deep(.el-table .el-table__footer-wrapper) {
  --el-table-row-hover-bg-color: rgb(128, 255, 0);
}
</style>
